package com.wit.witmg.api;


import com.wit.witmg.service.ITHrService;
import com.wit.witmg.util.JsonResult;
import com.wit.witmg.util.ModbusReader;
import com.wit.witmg.util.TemperatureController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;

/**
 * @author bob
 * @since 2024-12-20
 */
@RestController
@RequestMapping("modbus")
@Api(tags = "五面炉API")
public class ModbusController {

    @ApiOperation("获取数据")
    @PostMapping("get")
    public Object get(HttpServletRequest request) {
        ModbusReader reader = new ModbusReader("60.190.91.134", 5001, 1);
        int[] inputRegs;
        try {
            if (reader.connect()) {
                System.out.println("TCP连接成功");
                // 读取输入寄存器 (地址1开始，读取2个寄存器)
                inputRegs = reader.readInputRegisters(1, 10);
            } else {
                reader.disconnect();
                return JsonResult.error("连接失败");
            }
        } catch (IOException e) {
            reader.disconnect();
            return JsonResult.error("通信错误");
        } finally {
            reader.disconnect();
        }
        return JsonResult.success(inputRegs);
    }

    @ApiOperation("设置数据")
    @PostMapping("set")
    public Object set(HttpServletRequest request,
                      @RequestParam("wd") Integer wd) {
        TemperatureController controller = new TemperatureController("60.190.91.134", 5001, 1);

        try {
            if (controller.connect()) {
                System.out.println("连接设备成功");

                // 示例1: 设置单个温度值到地址1
                boolean success1 = controller.setSingleTemperature(1, wd); // 25.0°C (缩放10倍)
                System.out.println("设置单个温度: " + (success1 ? "成功" : "失败"));
                controller.disconnect();
                return JsonResult.success("设置单个温度: " + (success1 ? "成功" : "失败"));

            } else {
                System.out.println("连接设备失败");
                controller.disconnect();
                return JsonResult.error("连接设备失败");
            }
        } catch (IOException e) {
            System.err.println("通信错误: " + e.getMessage());
            controller.disconnect();
            return JsonResult.error("通信错误");
        }

    }
}
